package com.miao.common.ws;


import com.alibaba.fastjson.JSON;
import com.miao.common.entity.Message;
import com.miao.common.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/common/webSocket/{type}/{uid}/{storeId}")
@Component
public class WebSocketServer {


    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();





    private static ApplicationContext applicationContext;
    private static ChatService chatService;


    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
        chatService=applicationContext.getBean(ChatService.class);
    }


    //发送消息
    public void sendMessage(Session session, String message) {
        if (session != null) {
            synchronized (session) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String userId, String message) {
        Session session = sessionPools.get(userId);
        sendMessage(session, message);

    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String userId, @PathParam(value = "type") String type, @PathParam(value = "storeId") String storeId) {


        System.out.println(userId+"建立连接 "+ "类型:"+type+" 店铺id:"+storeId);
        //如果type =1 则为 客服客户端 将客服加入 店铺的客服列表
        if ("1".equals(type)) {
            chatService.onlineWaiter(storeId, userId);
        }
        //建立连接 如果type =2 顾客客户端
        if ("2".equals(type)) {
            //检查在session中是否有已经存在的客服端session
            Session session1 = sessionPools.get(userId);
//            if (null != session1) {
//                //推送消息 关闭老的客户端
//                sendInfo(userId, "您建立了新的回话当前回话已关闭。");
//            } else {
//                this.sendMessage(session, "您好！欢迎使用 秒优购");
//            }
            //加入等待服务队列

            chatService.pushWaitQueue(storeId,userId);
        }
        //建立连接  将客服 或购物者 session放入 sessionPools中
        sessionPools.put(userId, session);



    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "uid") String userId, @PathParam(value = "type") String type, @PathParam(value = "storeId") String storeId) {
        //客户端断开连接 从sessionPools中移除回话
        sessionPools.remove(userId);

        if ("1".equals(type)) {
            //如果type =1 则为 客服客户端 将客服 断开连接
            chatService.outlineWaiter(storeId, userId);
        }
        if ("2".equals(type)) {
            //如果type =2 则为 顾客客户端
            //从等待队列移除
            chatService.popWaitQueue(storeId,userId);
        }

    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message1) throws IOException {

        //如果id为 99999 则为机器人对话
        Message message = JSON.parseObject(message1, Message.class);
        if(!message.getReceiveId().equals("99999")){
            sendInfo(String.valueOf(message.getReceiveId()), message1);
            chatService.saveMessageRecord(message);
        }else {
            String s = chatService.robotWaiter(message.getMsg());

            HashMap<String, String> messageS = new HashMap<>();
            messageS.put("type","1");
            messageS.put("msg",s);
            messageS.put("storeId",message.getStoreId());
            messageS.put("sendId","99999");
            messageS.put("receiveId",message.getSendId());
            messageS.put("receiveAvatar",message.getReceiveAvatar());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            messageS.put("sendTime",simpleDateFormat.format(new Date()));

            sendInfo(String.valueOf(message.getSendId()),JSON.toJSONString(messageS));
            Message newMessage = new Message();
            newMessage.setType("1");
            newMessage.setMsg(s);
            newMessage.setStoreId(message.getStoreId());
            newMessage.setSendId("99999");
            newMessage.setReceiveId(message.getSendId());
            newMessage.setReceiveAvatar(message.getReceiveAvatar());
            newMessage.setSendAvatar(message.getSendAvatar());
            newMessage.setSendTime(new Date());
            chatService.saveMessageRecord(message);
            chatService.saveMessageRecord(newMessage);
        }



    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }


}
